package controller

import (
	"context"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/olivere/elastic/v7"
	"net/http"
	"testGin/entity"
	"testGin/tool"
)

func Search(c *gin.Context) {
	search := entity.GetSearch(c)
	searchSource := elastic.NewSearchSource()
	searchSource = searchSource.Query(elastic.NewMatchQuery("title", search.Title))
	searchResult, _ := GetES().Search().Index("es_qiniu").SearchSource(searchSource).Do(context.Background())
	var videos []entity.Video
	info, err := tool.ParseToken(c.GetHeader("Authorization"))
	for _, hit := range searchResult.Hits.Hits {
		json.Unmarshal(hit.Source, &search)
		var video entity.Video
		GetDB().Where("id = ?", search.Id).First(&video)
		video.Url = "http://" + Domain + "/" + video.Key
		video = getCollectAndLoveNum(video)
		if err == nil {
			video = isCollectAndLove(info.UserId, video)
		}
		videos = append(videos, video)
	}
	videos = VideosFill(videos)
	c.JSON(http.StatusOK, tool.R{
		200, "ok", videos,
	})
}
